// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
module.exports = {
	_before: function () { // 通用预处理器

	},
	
	/**
	 * 获取列表
	 * @param {string} openid 
	 * @param {number} pageIndex 
	 * @param {number} pageSize 
	 */
	async getList(openid, pageIndex = 1, pageSize = 100) {
		const dbjql = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		});
		const res = await dbjql.collection("mytoolshistory").where({
			onlyid: openid
		}).skip((pageIndex - 1) * pageSize).limit(pageSize).get();
		return res;
	},
	
	/**
	 * 添加记录
	 * @param {Object} item
	 */
	async add(openid, item) {
		const dbjql = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		});

		const res = await dbjql.collection('mytoolshistory').where({
			onlyid: openid,
			name: item.name
		}).get();
		let resRight = null;
		// 有就更新，没有就是添加
		if (res.code === 0 && res.data && res.data.length > 0) {
			resRight = await dbjql.collection('mytoolshistory').doc(res.data[0]._id).update({
				date: Date.now(),
				count: res.data[0].count + 1
			});
		} else {
			resRight = await dbjql.collection('mytoolshistory').add(item);
		}
		return resRight;
	},
	
	/**
	 * 删除搜索记录
	 * @param {string} openid 
	 * @param {string} id 
	 */
	async delete(openid, id) {
		const dbjql = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		});
		const res = await dbjql.collection('mytoolshistory').where({
			onlyid: openid,
			_id: id
		}).remove();
		return res;
	}
}
